package org.lanqiao.taru.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.lanqiao.taru.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
public class TokenInterceptor   implements HandlerInterceptor {

    private static  final  String  OPTIONS="OPTIONS";

    @Value("${my.jwt.enable}")
    Boolean  enable;
    @Value("${my.jwt.tokenKey}")
    String   tokenKey;    //tokenKey =x-custom-token

    @Autowired
    JwtUtil  jwtUtil;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("已经拦截了请求:{}   ,请求方法是{}",request.getRequestURL(),request.getMethod());
            //放行预检请求
            if(OPTIONS.equals(request.getMethod())){
                    return true;
            }
            log.info("----------------{}",enable);
            if(!enable){
                return   true;
            }

        String token =request.getHeader(tokenKey);
        log.info("接口的Token是:{}",token);
        if(token!=null){
            //验证token的合法性
            boolean  isValid =jwtUtil.validateToken(token);
            if(isValid){
                log.info("接口Token合法");
                return true;
            }

        }
        log.info("接口Token不合法");
        //告诉前端 你没有令牌 通过http状态吗 401
        response.setStatus(401);
        response.setContentType("text/plain;charset=utf-8");
        response.getWriter().write("没有有效的token令牌，请重新登录");
       return  false;
    }
}
